<?php


namespace app\api\controller;

use app\service\JwtService;

class MiniProgram extends Base
{
    public function login()
    {
        $code = $this->request->param('code', '');
        if (!$code) {
            return apiReturnData(-1, '', '请提供code参数');
        }
        try {
            $getUserInfo = app()->WechatMiniProgram->auth->session($code); //获取用户信息;
            if ($getUserInfo && isset($getUserInfo['openid'])) {
                // 生成JWT Token
                $token = JwtService::createToken([
                    'openid' => $getUserInfo['openid'],
                    'session_key' => $getUserInfo['session_key'] ?? '',
                ]);
                return apiReturnData(1, ['token' => $token, 'expire_time' => JwtService::$ExpireTime], 'ok');
            } else {
                return apiReturnData(-1, '', '获取用户信息失败');
            }
        } catch (\Exception $e) {
            return apiReturnData(-1, '', $e->getMessage());
        }
    }
}